package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.business.utils.JsonUtil;
import com.dmcb.common.business.utils.ListUtil;
import com.dmcb.common.business.utils.WebUtil;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.XiNiuGuShiParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 63221_000 on 2016/8/1 0001.
 */
@Service
public class XiNiuGuShiCrawler extends BaseCrawler {
    Logger logger = LoggerFactory.getLogger(JianshuCrawler.class);

    @Autowired
    private XiNiuGuShiParser xiNiuGuShiParser;

    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Override
    protected String url() {
        return CrawlConstant.XINIUGUSHI_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.XINIUGUSHI_TAG;
    }

    @Override
    protected String avatarSelect() {
        return "div.user-image>img";
    }

    @Override
    protected String channelNameSelect() {
        return "h1.user-name";
    }


    @Override
    protected String listSelect() {
        return "div.wwgs1>div";
    }

    @Override
    protected String titleSelect() {
        return "h2.article-title>a";
    }

    @Override
    protected String authorSelect() {
        return "h1.user-name";
    }

    @Override
    protected String authorLink() {
        return "a.niming";
    }

    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章
        int totalAll = 0;
        link = link.trim();
        int uId =Integer.parseInt(link.substring(link.indexOf("?")+1,link.length()));
        for (int i = 0; true; i += 20) {
            String json = WebUtil.sendPost("http://www.xiniugushi.com/function/story.inc.php?action=userstorylist", "start=" + i + "&limit=20&uid="+uId);
            Map<String, Object> objectMaps = JsonUtil.getResult(json);
            if (objectMaps.get("data") == "[]") {
                break;
            }
            List<Map<String,Object>> mapList = (ArrayList)objectMaps.get("data");
            if (ListUtil.isEmpty(mapList)) {
                break;
            }

            JsonResult result =     iterate(authorId, mapList);
            if (!result.isSuccess()) {
                return result;
            }
            totalAll += result.getInt();
        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult iterate(int authorId, List<Map<String, Object>> mapList) {

        int succ = 0;

        int exist = 0;
        for (Map<String, Object> map : mapList) {
            // 获取标题、链接元素
            String title = WebUtil.URLDecode((String) map.get("title"));
            if (StringUtils.isBlank(title)) {
                continue;
            }
            try {
                // 校验作者、标题是否已存在
                Article article = articleCrawlMapper.queryByAuthorTitle(authorId, title);
                if (article != null) {
                    exist++;
                    if (exist >= 6 && succ == 0) {
                        return success(succ);
                    }
                    continue;
                }
                String href = ((String) map.get("shareurl")).replace("\\", "");
                if (StringUtils.isBlank(href)) {
                    continue;
                }
                JsonResult result = parse(authorId, href);
                succ += result.isSuccess() ? 1 : 0;
            } catch (Exception e) {
                logger.error("Parser.parse error,{}", title, e);
                return error(CommonConstant.ABNORMAL_MSG);
            }
        }
        return success(succ);
    }


    @Override
    protected JsonResult iterate(int authorId, Document doc) {
        return super.iterate(authorId, doc);
    }

    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return xiNiuGuShiParser.parse(authorId, link);
    }

    @Override
    protected String getBody(Document doc) {
        return xiNiuGuShiParser.getBody(doc);
    }
}

